package org.az.netty_study.p14_netty综合案例2_聊天室.client;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.webservice.SoapUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.az.netty_study.p14_netty综合案例2_聊天室.message.*;
import org.az.netty_study.p14_netty综合案例2_聊天室.protocol.MessageCodecSharable;
import org.az.netty_study.p14_netty综合案例2_聊天室.protocol.ProcotolFrameDecoder;

import java.util.Arrays;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

@Slf4j
public class ChatClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);
        AtomicBoolean isLogin = new AtomicBoolean(false);
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {

                    ch.pipeline().addLast(new ProcotolFrameDecoder());
                    //ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    //客户端的IdleStateHandler，当指定时间没有向channel写数据，则触发写空闲事件
                    ch.pipeline().addLast(new IdleStateHandler(0, 3, 0));
                    //当指定时间没有向channel写数据，则向服务器发送心跳表示自己还活着
                    ch.pipeline().addLast(new ChannelDuplexHandler() {
                        //特殊事件处理器
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            if (evt instanceof IdleStateEvent event) {
                                //表示触发了写空闲事件
                                if (event.state() == IdleState.WRITER_IDLE) {
                                    log.info("客户端发送心跳");
                                    ctx.writeAndFlush(new PingMessage());
                                }
                            }
                        }
                    });

                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            log.info("{}", msg);
                            //如果返回的是登录
                            if (msg instanceof LoginResponseMessage resMsg) {
                                if (resMsg.isSuccess()) {
                                    //登录成功
                                    isLogin.set(true);
                                }
                                WAIT_FOR_LOGIN.countDown();
                            }
                        }
                    });

                    ch.pipeline().addLast("client handler", new ChannelInboundHandlerAdapter() {
                        //连接建立时触发的回调
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            new Thread(() -> {
                                Scanner scanner = new Scanner(System.in);
                                System.out.println("请输入用户名");
                                String username = scanner.nextLine();
                                System.out.println("请输入密码");
                                String password = scanner.nextLine();

                                //根据输入构造登录请求对象
                                LoginRequestMessage msg = new LoginRequestMessage(username, password);
                                //发送消息，这个方法会立即从当前handler开始向上找出站handler
                                ctx.writeAndFlush(msg);
                                System.out.println("等待后续操作");
                                try {
                                    WAIT_FOR_LOGIN.await();
                                } catch (InterruptedException e) {
                                    throw new RuntimeException(e);
                                }
                                //登录失败
                                if (!isLogin.get()) {
                                    ctx.channel().close();
                                    return;
                                }
                                while (true) {
                                    System.out.println("==================================");
                                    System.out.println("send [username] [content]");
                                    System.out.println("gsend [group name] [content]");
                                    System.out.println("gcreate [group name] [m1,m2,m3...]");
                                    System.out.println("gmembers [group name]");
                                    System.out.println("gjoin [group name]");
                                    System.out.println("gquit [group name]");
                                    System.out.println("quit");
                                    System.out.println("==================================");

                                    //假设输入的格式是正确的
                                    String command = scanner.nextLine();
                                    String[] s = command.split(" ");
                                    Message message = null;
                                    switch (s[0]) {
                                        case "send":
                                            message = new ChatRequestMessage(username, s[1], s[2]);
                                            break;
                                        case "gsend":
                                            message = new GroupChatRequestMessage(username, s[1], s[2]);
                                            break;
                                        case "gcreate":
                                            Set<String> members = Arrays.stream(s[2].split(",")).collect(Collectors.toSet());
                                            members.add(username);
                                            message = new GroupCreateRequestMessage(s[1], members);
                                            break;
                                        case "gmembers":
                                            message = new GroupMembersRequestMessage(s[1]);
                                            break;
                                        case "gjoin":
                                            message = new GroupJoinRequestMessage(username, s[1]);
                                            break;
                                        case "gquit":
                                            message = new GroupQuitRequestMessage(username, s[1]);
                                            break;
                                        case "quit":
                                            break;
                                        default:
                                            System.out.println("输入有误，请重新输入");
                                            continue;
                                    }
                                    if (message != null) {
                                        ctx.writeAndFlush(message);
                                    } else {
                                        ctx.channel().close();
                                        break;
                                    }
                                }
                            }).start();
                        }
                    });
                }
            });
            Channel channel = bootstrap.connect("localhost", 8080).sync().channel();
            //在channel关闭之前，会一直阻塞
            channel.closeFuture().sync();
        } catch (Exception e) {
            log.error("client error", e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
